package com.cff.shorturl.http.handler.inter;

import java.io.IOException;
import java.net.URISyntaxException;

import com.cff.shorturl.context.Context;
import com.cff.shorturl.http.body.HttpRequestMsg;
import com.cff.shorturl.http.body.HttpResponseMsg;
import com.cff.shorturl.http.body.ResCode;
import com.cff.shorturl.http.body.ResType;
import com.cff.shorturl.http.handler.ResourceHandler;
import com.cff.shorturl.util.StringUtil;
import com.cff.shorturl.util.Utils;

public class StaticResourceHandler extends ResourceHandler {
	public static final String baseUrl = "/";
	@Override
	public HttpResponseMsg handle(HttpRequestMsg msg) throws IOException, URISyntaxException {
		String url = msg.getUrl();
		if(StringUtil.isEmpty(url)|| baseUrl.equals(url)){
			url = Context.getString("welcom");
		}
		String is = Utils.getFile(url);
		HttpResponseMsg hrm = msg.getReponse();
		hrm.setResCode(ResCode.OK.getValue());
		hrm.setMessage(is);
		ResType resType = getType(url);
		hrm.setResType(resType.getValue());
		return hrm;
	}

	public ResType getType(String path) {
		if (path.lastIndexOf(".") == -1)
			return ResType.HTML;
		String end = path.substring(path.lastIndexOf(".") + 1);
		if (StringUtil.isEmpty(end))
			return ResType.HTML;
		return ResType.enumTypeIgnoreCase(end);
	}

}
